﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Sales
{	public partial class CustomerReturn : CashOperation
	{	public	DIProject.DataSets.Sales.NewCustomerReturnDocRow NewDoc{get{return newDoc;}}
		private	DIProject.DataSets.Sales.NewCustomerReturnDocRow newDoc = null;

		public override decimal Sum
		{	get
			{	object s = sales.CustomerReturnLines.Compute(string.Format("sum({0})", retailSumDataGridViewTextBoxColumn.DataPropertyName), null);
				return s is decimal? (decimal)s: 0m;
			}
		}

		public	int ContragentDocId{get{return (int)contragentDocId;}}
		public	DateTime ContragentDocDate{get{return (DateTime)contragentDocDate;}}
		public	string ContragentDocNumber{get{return contragentDocNumber;}}
//-------------------------------------------------------------------------------------------------
		private ToolStripMenuItem ownerItem = null;

		private CustomerReturn() : this(null)	// Для дизайнера
		{
		}

		public CustomerReturn(ToolStripMenuItem ownerItem) : base(null)	// форма только одна, а не для каждой кассы
		{	InitializeComponent();

			if(ownerItem != null)
			{	this.ownerItem	= ownerItem;
				ownerItem.Tag	= this;
			}
		}

		protected override void OnFormClosed(FormClosedEventArgs e)
		{	base.OnFormClosed(e);

			if(ownerItem != null)
				ownerItem.Tag = null;
		}
//-------------------------------------------------------------------------------------------------
		protected override void SetCaption()
		{	Text = string.Format
			(	TextFormat
			,		newDoc != null && newDoc.RowState != DataRowState.Detached
				?	newDoc.DocNumber
				:	Properties.Resources.strUndefined
			,	Sum.ToString("N2")
			,		ContragentDocNumber != null
				?	ContragentDocNumber
				:	Properties.Resources.strUndefined
			);
		}

		private void CustomerReturn_Load(object sender, EventArgs e)
		{	EnableControls(false);
			qnttyDataGridViewTextBoxColumn1.HeaderText = "К возврату";
			toolStripButtonCreate.	Text = "Новый возврат";
			toolStripButtonClose.	Text = "Закрыть возврат";
			toolStripButtonCancel.	Text = "Аннулировать возврат";
			cashRegisterLines.DataSource = customerReturnLinesBindingSource;
			sales.CustomerReturnLines.CustomerReturnLinesRowDeleted += new DIProject.DataSets.Sales.CustomerReturnLinesRowChangeEventHandler(CustomerReturnLinesRowDeleted);
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void EnableControls(bool enable)
		{	modified = enable;
			toolStripButtonCreate.	Enabled = !enable;
			toolStripButtonRefresh.	Enabled = newDoc != null && newDoc.RowState != DataRowState.Detached;
			toolStripButtonClose.	Enabled = enable;
			toolStripButtonCancel.	Enabled = enable;
			textBoxQntty.			Enabled = enable;
			textBoxBarcode.			Enabled = enable;
			textBoxName.			Enabled = enable;
			searchedGoods.			Enabled = enable;
			cashRegisterLines.		Enabled = enable;
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
// Операции с документом
		protected override void RefreshDoc()
		{	try
			{	customerReturnLinesTableAdapter.Fill(sales.CustomerReturnLines, newDoc.Id);
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		protected override void CreateNewDoc()
		{	DIProject.Sales.CashReceiptChoice cashReceiptChoice = new DIProject.Sales.CashReceiptChoice();
			if(cashReceiptChoice.ShowDialog(this) == DialogResult.OK)
			{	contragentDocId		= cashReceiptChoice.DocId;
				contragentDocDate	= cashReceiptChoice.DocDate;
				contragentDocNumber	= cashReceiptChoice.DocNumber;
				try
				{	newCustomerReturnDocTableAdapter.Fill
					(	sales.NewCustomerReturnDoc
					,	DateTime.Now		// DocDate
					,	null				// DocNumber
					,	ContragentDocDate	// ContragentDocDate
					,	ContragentDocNumber	// ContragentDocNumber
					,	null				// Note
					,	DateTime.Now		// MD
					,	FirstForm.Login		// MW
					);
					newDoc = sales.NewCustomerReturnDoc[0];
					customerReturnLinesTableAdapter.Fill(sales.CustomerReturnLines, newDoc.Id);

					EnableControls(true);
					ActiveControl = textBoxBarcode;
				}
				catch(SqlException eq)
				{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}

		protected override void CloseNewDoc()
		{	try
			{	EnableControls(false);
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		protected override void CancelNewDoc()
		{	try
			{	if(newDoc != null)
				{	newDoc.Delete();
					newCustomerReturnDocTableAdapter.Update(sales.NewCustomerReturnDoc);
					sales.CustomerReturnLines.Rows.Clear();
					contragentDocId		= null;
					contragentDocDate	= null;
					contragentDocNumber	= null;
					EnableControls(false);
				}
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
//-------------------------------------------------------------------------------------------------
// Операции со строками документа
		protected override bool LineInsert()
		{	int qntty;
			bool ok = false;
			if(newDoc != null
			&& SearchedGoodsRow != null
			&& (qntty = int.Parse(textBoxQntty.Text)) > 0
			&& qntty <= SearchedGoodsRow.Qntty)
			{	DIProject.DataSets.Sales.CustomerReturnLinesRow newLine = sales.CustomerReturnLines.NewCustomerReturnLinesRow();
				try
				{	newLine.DocId		= newDoc.Id;
					newLine.ReturnLineId= SearchedGoodsRow.ReturnLineId;
					newLine.PartyId		= SearchedGoodsRow.PartyId;
					newLine.Name		= SearchedGoodsRow.Name;
					newLine.RetailPrice	= SearchedGoodsRow.RetailPrice;
					newLine.Qntty		= qntty;
					newLine.RetailSum	= qntty*SearchedGoodsRow.RetailPrice;
					newLine.Note		= null;
					newLine.MD			= DateTime.Now;
					newLine.MW			= FirstForm.Login;
					sales.CustomerReturnLines.AddCustomerReturnLinesRow(newLine);
					customerReturnLinesTableAdapter.Update(newLine);

					SearchedGoodsRow.Qntty -= qntty;
					SetCaption();

					ok = true;
				}
				catch(SqlException eq)
				{	newLine.RejectChanges();
					MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	newLine.RejectChanges();
					MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			else
				Console.Beep();
			return ok;
		}
		protected override bool LineUpdate(int rowIndex)
		{	DIProject.DataSets.Sales.CustomerReturnLinesRow changedLine = sales.CustomerReturnLines[rowIndex];
			try
			{	int origQntty = (int)changedLine[sales.CustomerReturnLines.QnttyColumn, DataRowVersion.Original];
				changedLine.BeginEdit();
				changedLine.RetailSum = changedLine.Qntty*changedLine.RetailPrice;
				changedLine.EndEdit();
				customerReturnLinesTableAdapter.Update(changedLine);
				SetCaption();

				return true;
			}
			catch(SqlException eq)
			{	changedLine.RejectChanges();
				MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	changedLine.RejectChanges();
				MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			return false;
		}

		private void CustomerReturnLinesRowDeleted(object sender, DIProject.DataSets.Sales.CustomerReturnLinesRowChangeEvent e)
		{	try
			{	customerReturnLinesTableAdapter.Update(e.Row);
				SetCaption();
			}
			catch(SqlException eq)
			{	e.Row.RejectChanges();
				MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	e.Row.RejectChanges();
				MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
//-------------------------------------------------------------------------------------------------
	}
}